<template>
  <div>
    <!--头文件-->
    <el-row>
      <div class="div-breadcrumb">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '' }">&#12288;&#12288;主页</el-breadcrumb-item>
          <el-breadcrumb-item>数据目录</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-row>
    <!--树结构  项目名称 目录  图层-->
    <el-row>
      <el-card>
        <div slot="header" class="clearfix">
          <i class="kfb-icon-yonghuzu"></i>
          <span>数据目录</span>
        </div>
        <div class="block">
          <el-tree
            :data="tableData"
            node-key="_id"
            default-expand-all
            :expand-on-click-node="false"
            :props="defaultProps"
            @node-drop="handleDrop"
            :allow-drop="allowDrop"
            :allow-drag="allowDrag"
          >
            <span class="custom-tree-node" slot-scope="{node, data}">
              <span>
                
                <i :class="data.pid ? 'kfb-icon-wenjianjiazhankai':'kfb-icon-kehuxinxiliebiao'">{{data.name}}</i>
              </span>
              <span>
                <el-button
                  icon="el-icon-circle-plus-outline"
                  type="text"
                  size="mini"
                  @click="() => append(data)"
                  :disabled="!isDir(node,data)"
                >添加</el-button>
                <el-button
                  icon="el-icon-edit"
                  type="text"
                  size="mini"
                  @click="() => modify(node, data)"
                 :disabled="isSelf(node, data) || !isDir(node,data)"
                >修改</el-button>
                <el-button
                  icon="el-icon-remove-outline"
                  type="text"
                  size="mini"
                  :disabled="isSelf(node, data)"
                  @click="() => remove(node, data)"
                >删除</el-button>

                <el-button
                  icon="el-icon-remove-outline"
                  type="text"
                  size="mini"
                  :disabled="!isDir(node,data) && !isLast(node, data)"
                  @click="() => guazai(node, data)"
                >挂载</el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-card>
    </el-row>
    <!--编辑对话框-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <div>
        <el-form ref="form" :model="form" label-width="80px" label-position="right" :rules="rules">
          <el-form-item label="目录名称" size="small" prop="label">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="目录路径" size="small" prop="path">
            <el-input v-model="form.path" disabled></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="handleConfirm('form')">确 定</el-button>
      </span>
    </el-dialog>

    <!--二维图层-->
    <el-dialog
      :title="form.name"
      :visible.sync="dialogVisible1"
      width="35%"
      height="200"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <div>
        <el-transfer
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入城市拼音"
          v-model="selectLayers"
          :titles="['可选图层', '已选图层']"
          :props="{key:'_id',label:'name'}"
          :data="allLayers"
        ></el-transfer>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAttrConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <!--三维图层-->
    <el-dialog
      :title="form.name"
      :visible.sync="dialogVisible2"
      width="35%"
      height="200"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <div>
        <el-transfer
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入城市拼音"
          v-model="selectScenes"
          :titles="['可选图层', '已选图层']"
          :props="{key:'_id',label:'name'}"
          :data="allScenes"
        ></el-transfer>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAttrConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>



<script>
import { add, remove, update, list, getdir } from "@/api/yxwh/sjml";
import { listLayers } from "@/api/yxwh/slzt";
import { listScenes, listScenesByType } from "@/api/yxwh/cjzt";
import Clone from "@/utils/clone";

export default {
  name: "index",
  data() {
    return {
      form: {},
      isAdd: false,
      tableData: [],
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        path: [{ required: true, message: "请输入名称", trigger: "blur" }]
      },
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2:false,
      selectRow: undefined,
      defaultProps: { label: "name", children: "children" },
      allScenes: [],
      allLayers: [],
      selectLayers: [],
      selectScenes:[],
      selectedDistData: [],
      
    };
  },
  methods: {
     /**
     * 确定配置
     */
    handleAttrConfirm() {
       if(this.selectRow.type===0){ 
         //更新
           update({_id:this.selectRow._id,children:this.selectLayers,islayer:0}).then(res => {
              this.dialogVisible1 = false;
              //处理一些，不能重复
              this.selectRow.children = this.selectRow.children.filter(i=>i.pid).concat(this.allLayers.filter(i=>this.selectLayers.indexOf(i._id)!=-1));
              //this.selectRow.islayer = this.selectLayers.length > 0 ? 1:0
            });
       }else{
            update({_id:this.selectRow._id,children:this.selectScenes,islayer:0}).then(res => {
              this.dialogVisible2 = false;
              this.selectRow.children = this.selectRow.children.filter(i=>i.pid).concat( this.allScenes.filter(i=>this.selectScenes.indexOf(i._id)!=-1));
              //this.selectRow.islayer = this.selectScenes.length > 0 ? 1:0
            });
       }
    },

   handleAttrConfirmScene(){
          
   },


    /**
     * 关闭
     * @param done
     */
    handleClose(done) {
      done();
    },
    filterMethod(query, item) {
      return item.name.indexOf(query) > -1;
    },
    /**
     * 获取所有图层(subject类型的图层)
     */
    getAllLayers() {
      listLayers("subject").then(res => {
        this.allLayers = res.data.filter(item =>
          item.dept.startsWith(this.$store.getters.dept)
        );
      });
    },

    /**
     * 获取所有的场景数据
     */
    getAllScenes() {
      listScenesByType("scene").then(res => {
        this.allScenes = res.data.filter(item =>
          item.dept.startsWith(this.$store.getters.dept)
        );
      });
    },

  
   //拖拽
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("tree drop: ", dropNode.label, dropType);
    },


    allowDrop(draggingNode, dropNode, type) {
      return draggingNode.data.type === dropNode.data.type;
    },



    allowDrag(draggingNode) {
      return draggingNode.data.pid !== "Map" || draggingNode.data.pid !== "Map";
    },

    /**
     * 根目录
     * @param node
     * @param data
     * @returns {boolean}
     */
    isSelf(node, data) {
      return !data.pid || (data.pid === "Map" || data.pid === "Scene") ;
    },

    isDir(node,data){
      return data.pid;
    },

    isLast(node, data) {
      return (data.children && data.children.length === 0);
    },

    /**
     * 挂载
     */
    guazai(node, data) {
      this.selectRow = data;
      if (data.type === 0) {
        //地图
        this.dialogVisible1 = true;
        this.selectLayers = data.children.filter(i=>!i.pid).map(o => o._id);
        this.getAllLayers();
      } else {
        //场景
        this.dialogVisible2 = true;
        this.selectScenes = data.children.filter(i=>!i.pid).map(o => o._id);
        this.getAllScenes();
      }
    },
    /**
     * 添加和修改
     */
    handleConfirm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isAdd) {
            add(this.form).then(res => {
              this.dialogVisible = false;
              this.selectRow.children.push(res.data);
            });
          } else {
            update(this.form).then(res => {
              this.dialogVisible = false;
              this.selectRow.name = this.form.name;
            });
          }
        }
      });
    },
    /**
     * 添加
     * @param data
     */
    append(data) {
      this.isAdd = true;
      this.dialogVisible = true;
      if (!data.children) {
        this.$set(data, "children", []);
      }
      this.selectRow = data;
      this.form = {
        name: "",
        path: data.path + data._id + "/",
        children: [],
        pid: data._id,
        islayer: 0,
        level: data.level + 1,
        type: data.type
      };
    },
    /**
     * 修改
     * @param node
     * @param data
     */
    modify(node, data) {
      this.isAdd = false;
      this.dialogVisible = true;
      this.selectRow = data;
      this.form = Clone.clone(data);
    },
    /**
     * 删除
     * @param node
     * @param data
     */
    remove(node, data) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          remove({ _id: data._id }).then(res => {
            const parent = node.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex(d => d._id === data._id);
            children.splice(index, 1);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  },
  mounted: function() {
    /**
     * 查询
     */
    list().then(res => {
      //组织一下数据
      var data = res.data;
      this.tableData = data.filter(i => {
        if (i.islayer == 0 && i.children.length == 0) {
          i.children = data.filter(item => item.pid === i._id);
        }else{
          i.children = i.children.concat(data.filter(item => item.pid === i._id))
        }
        return i.level == 0;
      });
    });
  },
  computed: {
    /**
     * 对话框标题
     * @returns {string}
     */
    title() {
      return this.isAdd ? "添加" : "修改";
    }
  }
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.kfb-icon-yonghuzu {
  margin: 0 5px 0 2px;
}

.div-breadcrumb {
  border-radius: 4px;
  min-height: 48px;
  background: #99a9bf;
  display: flex;
  align-items: center;
  font-size: 24px;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
